<template>
	<view>
		<view class="page">
			<view class="cardView">
				<view class="oper-text">
					<text>{{selectedRow.operatorName}}</text>
				</view>
				
				<view class="commitment-container">
					<view class="container">
						<text>根据《食品生产许可管理办法》 《食品生产许可审查通则》 </text>
						<view class="edit-item" @click="handleInput('guidelines')">
							《 {{ selectedRow.guidelines || '编辑' }}》
						</view>
						<text>,定于</text>
						<view class="edit-item" @click="openDatePicker('checkStartTime')">
							{{ selectedRow.checkStartTime || '编辑' }}
						</view>
						<text>至</text>
						<view class="edit-item" @click="openDatePicker('checkEndTime')">
							{{ selectedRow.checkEndTime  || '编辑' }}
						</view>
						<text>对你(单位)申请的</text>
						<view class="edit-item" @click="handleInput('applicationContent')">
							{{ selectedRow.applicationContent  || '编辑' }}
						</view>
						<text>食品生产许可进行现场调查。先将有关事项通知如下：</text>
					</view>

				</view>

				<view class="oneView">
					<uni-title type="h1" title="一.现场核查组" align="center"></uni-title>


					<view class="commitment-container">
						<view class="container">
							<text>包括核查组长</text>
							<view class="edit-item" @click="handleInput('groupLeader')">
								{{ selectedRow.groupLeader || '编辑' }}
							</view>
							<text>人、组员</text>
							<view class="edit-item" @click="handleInput('teamMembers')">
								{{ selectedRow.teamMembers || '编辑' }}
							</view>
							<text>人、观察员</text>
							<view class="edit-item" @click="handleInput('observer')">
								{{ selectedRow.observer || '编辑' }}
							</view>
							<text>共</text>
							<view class="edit-item" @click="handleInput('peopleNum')">
								{{ selectedRow.peopleNum || '编辑' }}
							</view>
							<text>人。</text>
						</view>




					</view>
					<view class="oneView">
						<uni-title type="h1" title="二.核查事项" align="center"></uni-title>
						<uni-title type="h2" title="□为选择项,在选择项框内打'√'" align="center"></uni-title>


						<view class="check-groups">
							<!-- 第一组（新申证） -->
							<uni-group mode="card">
								<template v-slot:title>
									<view class="uni-group_title">
										<uni-data-checkbox v-model="selectedRow.newCert" :localdata="firstGroupTitle"
											mode="list" @change="handleCerChangeTop" selectedColor="#2e31ee" />
									</view>
								</template>
								<uni-data-checkbox v-model="selectedRow.checkItemsOne" :localdata="product_apply_cer"
									mode="list" selectedColor="#2e31ee" @change="handleCerChange" />
							</uni-group>

							<!-- 第二组（变更/延续） -->
							<uni-group mode="card">
								<template v-slot:title>
									<view class="uni-group_title">
										<uni-data-checkbox v-model="selectedRow.newCert" :localdata="secondGroupTitle"
											@change="handleCerChangeTop" selectedColor="#2e31ee" />
									</view>
								</template>
								<uni-data-checkbox v-model="selectedRow.checkItemsOne" :localdata="product_apply_change"
									mode="list" selectedColor="#2e31ee" @change="handleCerChange" />
							</uni-group>
						</view>

						<view class="container">
							<view v-for="(item, index) in procedure_work" :key="item.value" class="list-item">
								<uni-title type="h1" :title="item.text" align="center"></uni-title>

								<view class="content-box">
									<text v-for="(line, lineIndex) in formatRemark(item.remark)" :key="lineIndex"
										class="content-text">
										{{line}}\n
									</text>
								</view>
							</view>
						</view>
					</view>
				</view>

			</view>
			<view class="cardView">
				<uni-title type="h1" title="部门公章" align="center"></uni-title>

				<!-- 经办人签名 -->
				<SignatureBlock :showSign="false" :show-stamp="true" label="承诺人"
					:sign-image.sync="selectedRow.checkPersonnelSignOne" :date.sync="selectedRow.officialSealDate" />
			</view>

			<view class="cardView">
				<uni-title type="h4" title="送达回执" align="center"></uni-title>
				<view class="commitment-container">
					<view class="container">
						<text>本企业已于</text>
						<view class="edit-item" @click="openDatePicker('deliveryReceiptTime')">
							{{ selectedRow.deliveryReceiptTime || '编辑' }}
						</view>

						<text> 收到《食品生产许可现场核查通知书》</text>
					</view>

				</view>
				<!-- 企业法人或负责人签名 -->
				<SignatureBlock :show-stamp="true" label="签字" :sign-image.sync="selectedRow.approverPersonSign"
					:date.sync="selectedRow.approverPersonDate" />

				<view class="commitment-container">
					<view class="container">
						<text>注：此通知书一式三份,一份由市场监督局保存,一份由市审评中心保存，一份由申请人保存。市审评中心联系电话：</text>
						<view class="edit-item" @click="handleInput('phone')">
							{{ selectedRow.phone || '编辑' }}
						</view>

						<text>。</text>
					</view>

				</view>
			</view>


		</view>

		<view v-if="editStatus!='FALSE'" class="button-container">
			<view class="button-save">
				<button style="flex: 1;" type="primary" @click="submitForm('1')">保存并提交核查通知书</button>
			</view>
			<view class="button-child">

				<button style="flex: 1;margin-right: 5px;" type="primary" @click="submitForm('0')">保存</button>
				<button style="flex: 1; margin-left: 5px;" type="warn" @click="goHome">返回工单创建页</button>

			</view>
		</view>

		<!-- 添加日期选择弹窗 -->
		<uni-popup ref="datePopup" type="dialog">
			<uni-popup-dialog mode="base" title="选择日期" @confirm="handleDialogConfirm" @close="handleDialogClose">
				<uni-datetime-picker type="date" @change="handleDateChange" />
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import stampSection from '@/components/order/stamp-section.vue'
	import SignatureBlock from '@/components/signature/signature.vue'
	import {
		foodProductionAdd,foodProductionUpdate,
		getMedicalDict,
		foodProductionInfo
	} from '@/api/order';
	export default {
		components: {
			SignatureBlock,
			stampSection
		},
		computed: {
			dateRangeDisplay() {
				if (this.selectedRow.checkStartTime && this.selectedRow.checkEndTime) {
					return `${this.selectedRow.checkStartTime} 至 ${this.selectedRow.checkEndTime}`
				}
				return ''
			},
			// 获取第一组标题选项（第一个元素）
			firstGroupTitle() {
				return this.check_category.length > 0 ? [this.check_category[0]] : []
			},
			// 获取第二组标题选项（第二、第三个元素）
			secondGroupTitle() {
				return this.check_category.slice(1, 3) // 截取索引1到2的元素
			}
		},
		data() {
			return {

				selectedDateRange: [], // 存储日期范围数组
				editStatus: 'ADD',
				selectedRow: {
					newCert: "", //组头选中项（单选）
					checkItemsOne: "", //组选中项（单选）
					workOrderId: "", //工单主键
					bidType: "",
					operatorName: "", //公司名称
					guidelines: "", //食品生产准则
					checkStartTime: "", //现场核查开始时间
					checkEndTime: "", //现场核查结束时间
					applicationContent: "", //申请的内容
					groupLeader: "", //组长
					teamMembers: "", //组员
					observer: "", //观察员
					peopleNum: "", //人数
					deliveryReceiptTime: "", //送达回执时间
					phone: "", //联系电话
					approverPersonSign: "", //签字
					approverPersonDate: "", //签字日期
					officialSealDate: "", //公章时间
					createBy: "",
					auditStatus: "1" //暂存给0,提交给1  

				},
				product_apply_cer: [],
				check_category: [],
				product_apply_change: [],
				procedure_work: [],
				editDateType: '',
				tempDate: ''
			}
		},


		onLoad(options) {
			if (options.editStatus != null) {
				const editStatus = decodeURIComponent(options.editStatus);
				const workOrderId = decodeURIComponent(options.workOrderId);
				this.selectedRow.workOrderId = workOrderId;
				this.editStatus = editStatus;
				this.getfoodProductionInfo(workOrderId);
			} else {
				if (options.orderData) {
					const orderData = JSON.parse(decodeURIComponent(options.orderData));
					const orderid = decodeURIComponent(options.workOrderId);
					this.selectedRow.bidType = orderData.bidType;
					this.selectedRow.workOrderId = orderid;
					this.selectedRow.operatorName = orderData.operatorName
					this.selectedRow.orderCategory = orderData.orderCategory;
				}
			}
			this.getMedicalDict('product_apply_cer');
			this.getMedicalDict('check_category');
			this.getMedicalDict('product_apply_change');
			this.getMedicalDict('procedure_work');
		},
		methods: {
			// 获取工单详情
			async getfoodProductionInfo(orderId) {
				const id = {
					workOrderId: orderId
				}
				const res = await foodProductionInfo(id);
				if (res.code === 0) {
					this.selectedRow = res.data;
				}
			},
			// 打开日期选择器
			openDatePicker(type) {
				this.editDateType = type;
				this.$refs.datePopup.open();
			},
			// 日期变化暂存
			handleDateChange(e) {
				this.tempDate = e ? new Date(e) : null;
			}, // 弹窗确认
			// 修改handleDialogConfirm方法
			handleDialogConfirm() {
				if (this.tempDate) {
					const year = this.tempDate.getFullYear();
					const month = (this.tempDate.getMonth() + 1).toString().padStart(2, '0');
					const day = this.tempDate.getDate().toString().padStart(2, '0');
					const formattedDate = `${year}-${month}-${day}`;
					if (this.editDateType === 'checkStartTime') {
						this.selectedRow.checkStartTime = formattedDate;
					} else if (this.editDateType === 'checkEndTime') {
						this.selectedRow.checkEndTime = formattedDate;
					} else if (this.editDateType === 'deliveryReceiptTime') {
						this.selectedRow.deliveryReceiptTime = formattedDate;
					}

				}

				this.$refs.datePopup.close();
			},
			handleDialogClose(){
				this.$refs.datePopup.close();
			},
			handleCerChange(e) {
				if (e.detail.value) {
					this.selectedRow.checkItemsOne = e.detail.value
				}
			},
			handleCerChangeTop(e) {
				if (e.detail.value) {
					this.selectedRow.newCert = e.detail.value
				}
			},
			formatRemark(remark) {
				// 处理HTML换行标签和特殊空格[3,4](@ref)
				return remark.replace(/<\/?br>/g, '\n') // 替换HTML换行标签
					.replace(/\s{10}/g, '') // 去除特殊空格
					.split('\n') // 按换行符分割
					.filter(line => line.trim()) // 过滤空行
			},
			handleChange(e) {
				console.log('选中项变更:', e.detail.value)
				// 可在此处添加业务逻辑处理
			},
			handleInput(type) {

				uni.showModal({
					title: `请输入信息`,
					content: this.selectedRow[type],
					editable: true,
					placeholderText: '请输入',
					success: res => {
						if (res.confirm) {
							const value = res.content.replace(/[^\d]/g, '') // 过滤非数字字符
							this.$set(this.selectedRow, type, res.content); // 确保响应式更新
							//this.selectedRow[type] = value || ''
						}
					}
				})
			},

			//获取字典值
			async getMedicalDict(type) {
				try {
					const res = await getMedicalDict(type)

					// 增加响应状态判断
					if (res.code === 0) {
						switch (type) {
							case 'product_apply_cer':
								this.product_apply_cer = res.data.map(item => ({
									text: item.label,
									value: String(item.value) // 确保字典值转为字符串
								}));
								break;

							case 'check_category':
								this.check_category = res.data.map(item => ({
									text: item.label,
									value: String(item.value) // 确保字典值转为字符串
								}));
								break;
							case 'product_apply_change':
								this.product_apply_change = res.data.map(item => ({
									text: item.label,
									value: String(item.value) // 确保字典值转为字符串
								}));

								break;
							case 'procedure_work':
								this.procedure_work = res.data.map(item => ({
									text: item.label,
									value: String(item.value), // 确保字典值转为字符串
									remark: item.remark
								}));


								break;

							default:
								return;
						}
					} else {
						throw new Error(res?.data?.msg || '接口返回异常')
					}

				} catch (error) {
					uni.showToast({
						title: error.message || '获取字典值失败',
						icon: 'none',
						duration: 2000
					})
				}
			},


			/// 提交方法
			async submitForm(status) {
				try {
					// 状态校验前置
					if (this.editStatus === 'FALSE') {
						return uni.showToast({
							title: '当前处于查看状态',
							icon: 'none'
						});
					}
					// 统一处理提交逻辑
					const isEditMode = this.editStatus === 'EDIT';
					const apiMethod = isEditMode ? foodProductionUpdate : foodProductionAdd;
					// 构造请求参数（避免污染原始数据）
					const payload = {
						...this.selectedRow,
						auditStatus: status,
					};

					// 显示加载状态
					uni.showLoading({
						title: '提交中...',
						mask: true
					});

					console.log(payload)
					// 执行API调用
					const res = await apiMethod(payload);

					if (res.code !== 0) {
						throw new Error(res.msg || '服务器处理异常');
					}

					// 统一处理成功逻辑
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});

				// 关闭当前页面，跳转到工单页
				this.$closeAndRedirect({
				  url: '/pages/work/history/index'
				});
				} catch (error) {
					// 统一错误处理
					console.error('提交失败:', error);
					uni.showToast({
						title: error.msg || '请求失败，请检查网络',
						icon: 'none',
						duration: 3000
					});
				} finally {
					uni.hideLoading();
				}
			},
			goHome() {
				uni.navigateBack({
					delta: 1
				});

			}
		}
	}
</script>


<style>
	.page {
		background-color: #e9f1fe;
		padding: 20px;
	}

	.cardView {
		margin-bottom: 10px;
		padding: 15px;
		background: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
	}

	.remark-text {
		font-size: 15px;
		line-height: 1.6;
		/* 关键行：设置行高 */
		display: block;
		/* 确保独占一行，行高生效 */
		margin-bottom: 8px;
		text-indent: 2em
			/* 可选：段落间距 */
	}

	.oneView {
		margin-top: 40px;

	}

	.commitment-container {
		text-indent: 2em;
		font-size: 16px;
	}

	.inline-block {
		display: inline-block;
	}

	.date-box {
		min-width: 4em;
		border-bottom: 1px solid #666;
		padding: 0 8rpx;
	}


	/* 如果需要更精确控制输入框位置 */
	.date-box2 input {
		padding-bottom: 1;
		/* 移除输入框自带的内边距 */
		margin-bottom: -2px;
		/* 微调位置 */
	}

	.production-input {
		border-bottom: 1px solid #666;
		padding: 0 8rpx;
		width: 200rpx;
	}

	.button-container {
		display: flex;
		background-color: #ffffff;
		width: 100%;
		padding: 10px;
		flex-direction: column;
		/* 垂直排列 */

		.button-save {
			margin-bottom: 10px;
		}

		.button-child {
			display: flex;
			flex-direction: row;
			/* 垂直排列 */

		}
	}

	.edit-item {
		display: inline-block;
		min-width: 80rpx;
		border-bottom: 1px solid #000000;
		color: #2e31ee;
		padding: 0 10rpx;
		margin: 0 8rpx;
	}



	/* 修改分组头背景色 */
	.uni-group_title {
		padding-left: 20px;
		background-color: #f1f4fd !important;
		/* 浅蓝色背景示例 */
	}

	/* 修改分组边框为蓝色虚线 */
	::v-deep .uni-group--card {
		border: 1px dashed #2e31ee !important;
		/* 使用uni-app主色或自定义蓝色 */
		border-radius: 8px;
		/* 可选圆角 */
	}

	.container {}

	.list-item {
		background: #fff;
	}

	.title {
		display: block;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}

	.content-box {
		padding-left: 20rpx;
	}

	.content-text {
		font-size: 16rpx;
		color: #000000;
		line-height: 1.6;
		display: block;
		padding-bottom: 10rpx;
	}


.oper-text{
	margin: 15px; font-size: 30px;color:#2e31ee
}
</style>